<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OAAdmin;
use App\Model\OAFinance;
use App\Model\OAProjectLx;
use App\Model\OAProjectYs;
use App\Model\OAStaff;
use App\Model\OATicket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class summaryLogic extends Controller
{
    public function getList($params)
    {
        try{
        $query = OAProjectLx::query();
        //年份
        if(isset($params['year']) && !empty($params['year'])){
            $year = $params['year'];
            $query->whereRaw("YEAR(`created_at`) = {$year}");
        }

        //公司ID
        if(isset($params['company_id']) && !empty($params['company_id'])){
            $query->where('gsid',$params['company_id']);
        }

        //部门ID
        if(isset($params['dept_id']) && !empty($params['dept_id'])){
            $query->where('deptid',$params['dept_id']);
        }

        //负责人ID
        if(isset($params['uid']) && !empty($params['uid'])){
            $query->where('uid',$params['uid']);
        }

        //客户ID
        if(isset($params['customer_id']) && !empty($params['customer_id'])){
            $query->where('partner_id',$params['customer_id']);
        }

        //项目ID
        if(isset($params['xmid']) && !empty($params['xmid'])){
            $query->where('id',$params['xmid']);
        }

        $list = $query->orderBy('updated_at','DESC')
                      ->paginate($params['page_size'],
                          ['id','uid','name',
                          'start','batch_id','uid',
                          'deptid','gsid','partner_id',
                          'created_at','offer','cost'
                          ]
                      )->toArray();

        $commonData = (new CommonLogic())->getCommonData(['dept','staff','company','customer']);
        $list['deptList'] = $deptList = array_column($commonData['dept'],'title','id');
        $list['staffList'] = $staffList = array_column($commonData['staff'],'username','id');
        $list['companyList'] = $companyList = array_column($commonData['company'],'name','id');
        $list['customerList'] = $customerList = array_column($commonData['customer'],'name','id');
        $list['yearList'] = range(2000,2099);
        $list['projectList'] = OAProjectLx::query()->pluck('name','id')->toArray();
        $companyTax = array_column($commonData['company'],'tax','id');
        if(empty($list['data'])) return $list;
        foreach ($list['data'] as &$data){
            $data['username'] = $staffList[$data['uid']] ?? '-';
            $data['company'] = $companyList[$data['gsid']] ?? '-';
            $data['tax'] = $companyTax[$data['gsid']] ?? 0;
            $data['customer'] = $customerList[$data['partner_id']] ?? '-';
            $data['dept'] = $deptList[$data['deptid']] ?? '-';
            $ysInfo = $this->getYsInfo($data['id']);
            $data = array_merge($ysInfo,$data);
            $data['ysmoney'] = $ysInfo['ysmoney'] = $ysInfo['is_ys'] ? $ysInfo['ysmoney'] : $data['offer'];
            $extralMoney = $this->getExtralMoney($data['id'],$ysInfo);
            $data = array_merge($extralMoney,$data);
            $data['ystime'] = $data['ystime'] == '-' ? $data['created_at'] : $data['ystime'];

        }
        return $list;
        }catch (\Exception $e){
            dd($e);
            throw new \Exception($e->getMessage());
        }
    }

    //获取预算信息
    protected function getYsInfo($xmid){
        $response = [
            'is_ys'=>0,
            'is_js'=>0,
            'ysmoney'=>0,
            'jsmoney'=>0,
            'cbmoney'=>0,
            'lrl'=>0,
            'lrmoney'=>0,
            'ystime'=>'-',
            'ysstart'=>'暂未结算',
            'ysstop'=>'暂未结算',
            'jsstart'=>'暂未结算',
            'jsstop'=>'暂未结算',
            'yscost'=>'暂未结算',
            'jscost'=>'暂未结算',
            'tax'=>0,
        ];
        $jsInfo = OAProjectYs::query()->where('xmid',$xmid)->where('type',2)->first();
        $ysInfo = OAProjectYs::query()->where('xmid',$xmid)->where('type',1)->first();

        if(is_null($jsInfo)){
            if(!is_null($ysInfo)){
                $response['is_ys'] = 1;
                $response['ysmoney'] = $ysInfo->offer;
                $response['yscost'] = $ysInfo->cost;
                $response['cbmoney'] = $ysInfo->total;//成本合计
                $response['lrl'] = $ysInfo->percent;
                $response['lrmoney'] = $ysInfo->profit;
                $response['tax'] = $ysInfo->tax;
            }
        }else{
            $response['yscost'] = $ysInfo->cost;
            $response['jscost'] = $jsInfo->cost;
            $response['ystime'] = $response['ysstart'] = $ysInfo->created_at;
            $response['ysstop'] = $ysInfo->updated_at;
            $response['is_ys'] = $response['is_js'] = 1;
            $response['jsmoney'] = $jsInfo->offer;
            $response['ysmoney'] = $ysInfo->offer;
            $response['cbmoney'] = $jsInfo->total;//成本合计
            $response['lrl'] = $jsInfo->percent;
            $response['lrmoney'] = $jsInfo->profit;
            $response['jsstart'] = $jsInfo->created_at;
            $response['jsstop'] = $jsInfo->updated_at;
            $response['tax'] = $jsInfo->tax;
        }
        //dd($response);
        return $response;
    }

    //获取发票金额
    protected function getExtralMoney($xmid,$ysInfo)
    {
        $offerMoney = $ysInfo['is_js'] ? $ysInfo['jsmoney'] : $ysInfo['ysmoney'];
        $response = [
            'waitMoney'=>'0.00',
            'yfMoney'=>'0.00',
            'fpMoney'=>'0.00',
            'skMoney'=>'0.00',
        ];
        $response['yfMoney'] = OAFinance::query()->where('xmid',$xmid)->whereNotIn('paytype',[5,9])->sum('money');
        $response['fpMoney'] = OAFinance::query()->where('xmid',$xmid)->where('paytype',5)->sum('money');
        $response['skMoney'] = OAFinance::query()->where('xmid',$xmid)->where('paytype',9)->sum('money');
        $response['waitMoney'] = resetMoney($offerMoney) - $response['yfMoney'];
        return $response;

    }

    //获取详情
    public function getSummaryDetail($input)
    {
        try {
            //dd(11);
            $xmid = $input['xmid'];
            $info = $this->getBaseInfo(['id'=>$xmid]);
            $info['leader'] = OAStaff::query()->where('id',$info['uid'])->value('username');
            $info = $info->toArray();
            $info['customer'] = $info['partner_id'];
            $ysinfo = $this->getYsInfo($xmid);
            $ysinfo['yscost'] = $ysinfo['yscost'] > 0 ? $ysinfo['yscost'] : $info['cost'];
            $ysinfo['jscost'] = $ysinfo['jscost'] > 0 ? $ysinfo['jscost'] : $info['cost'];
            $baseinfo = array_merge($info,$ysinfo);
            $baseinfo['lxcost'] = resetMoney($baseinfo['cost']);
            $baseinfo['lxmoney'] = $baseinfo['offer'];
            $jsMoney = $baseinfo['jsmoney'] > 0 ? $baseinfo['jsmoney'] : ($baseinfo['ysmoney'] > 0 ? $baseinfo['ysmoney'] : $baseinfo['offer']);
            $summaryTotal = [
                [
                    'financeTotal'=>0,
                    'adminTotal'=> 0,
                    'taxTotal'=> 0,
                    'incomeTotal'=> 0,
                    'outcomeTotal'=> 0,
                    'costTotal'=>0,
                    'offerTotal'=> 0,
                    'profitTotal'=> 0,
                    'rateTotal'=> 0
                ],
            ];

            $financeList = OAFinance::query()->where('xmid',$xmid)->select(['*'])->get()->toArray();
            $adminList = OAAdmin::query()->where('xmid',$xmid)->select('*')->get()->toArray();
            $financeTotal = array_sum(array_column($financeList,'money'));
            $adminTotal = array_sum(array_column($adminList,'money'));
            $summaryTotal[0]['financeTotal'] = $financeTotal;
            $summaryTotal[0]['adminTotal'] = $adminTotal;
            $summaryTotal[0]['taxTotal'] = $baseinfo['tax'];
            $summaryTotal[0]['incomeTotal'] = $baseinfo['lxmoney'];
            $summaryTotal[0]['outcomeTotal'] = $baseinfo['lxcost'];
            //dd($baseinfo['lxcost'],$financeTotal,$adminTotal,$baseinfo['tax']);
            $summaryTotal[0]['costTotal'] = $baseinfo['lxcost'] + $financeTotal + $adminTotal + $baseinfo['tax'];
            $summaryTotal[0]['offerTotal'] =  resetMoney($baseinfo['lxmoney']) + resetMoney($jsMoney);
            $summaryTotal[0]['profitTotal'] = $summaryTotal[0]['offerTotal'] - $summaryTotal[0]['costTotal'];
            $summaryTotal[0]['rateTotal'] = round($summaryTotal[0]['profitTotal'] / $summaryTotal[0]['offerTotal'] ,4) * 100;
            $summaryTotal[0]['rateTotal'] = strval($summaryTotal[0]['rateTotal']);
            $financeConfig = config('oa.finance');
            $adminConfig = config('oa.adminWork');
            $ticketConfig = config('oa.ticket');
            $ticketCategory = array_column($ticketConfig['category'],'value','id');
            $ticketType = array_column($ticketConfig['type'],'value','id');
            $fpList = $skList = [];

            if(!empty($financeList)){
                foreach ($financeList as &$finance){
                    $paytype =  $finance['paytype'];
                    $finance['type'] = $financeConfig[$paytype]['name'];
                    $finance['username'] = $baseinfo['leader'];
                    if($paytype == 5){
                        $finance['ticket_category'] = $ticketCategory[$finance['ticket_category']];
                        $finance['ticket_type'] = $ticketType[$finance['ticket_type']];
                        $finance['ticket_name'] = OATicket::query()->where('id',$finance['ticket_id'])->value('short_name');
                        $fpList[] = $finance;
                    }elseif($paytype == 9){
                        $finance['ticket_type'] = $ticketType[$finance['ticket_type']];
                        $skList[] = $finance;
                    }else{
                        //todo
                    }

                }
            }
            if(!empty($adminList)){
                foreach ($adminList as &$admin){
                    $admin['type'] = $adminConfig[$admin['type']]['work_name'];
                    $admin['username'] = $baseinfo['leader'];
                }
            }


            return [
                'baseinfo'=>$baseinfo,
                'summaryTotal'=>$summaryTotal,
                'financeList'=>$financeList,
                'adminList'=>$adminList,
                'fpList'=>$fpList,
                'skList'=>$skList,
            ];

        }catch (\Exception $e){
            throw new \Exception($e->getMessage().' on line '.$e->getLine());
        }
    }

}
